package com.itheima.common;

import com.itheima.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

// 异常处理器

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


   //  SQLIntegrityConstraintViolationException

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handle(SQLIntegrityConstraintViolationException ex){
        log.error("GlobalExceptionHandler::handle error",ex);
        String msg = ex.getMessage();
        if (msg.contains("Duplicate entry")){
            // 出现Duplicate entry 肯定是重复了
           return  R.error(msg.split(" ")[2]+"已存在,无法新增");
        }
        return R.error("服务器调皮了");
    }

    @ExceptionHandler(BizException.class)
    public  R<String> handler(BizException ex){
        log.error("业务异常: ", ex);
        return  R.error(ex.getMessage());
    }
}
